/**
 * @desc:扫码充值弹窗
 * @author:binlety
 * * */

import { useState, useEffect, useMemo } from 'react';
import { Form, Input, Button, Modal, message } from 'antd';
import CommonLoading from '@/components/CommonLoading';
import CommonModal from '@/components/CommonModal';
import { formatAmount, customTrimFunc } from '@/utils/utils.jsx';
import QRCode from 'qrcode.react';
import { getUnionRechargeRateOp, getPayQrcodeOp, pollFuncOp } from '../../../service';
import union_pay_img from '@/assets/yinlian.png';
import styles from './index.module.less';

let timerPoll,
  deadlineTimer,
	showText,
	backAmount = '0.00';

export default ({ accountMsg = {}, handleVisible, reloadFunc }) => {
	const [form] = Form.useForm();
	const [loading, setLoading] = useState(false);

	const [rateObj, setRateObj] = useState({})//费率
	const [serviceFee, setFee] = useState('0.00') //手续费
	const [disAmount, setDisAmount] = useState('0.00') //优惠金额
	const [finallyAmount, setAmount] = useState('0.00') //实际付款金额

	const [qrcode, setQrcode] = useState('')//支付二维码

	const rote = useMemo(() => {
		if (Object.keys(rateObj).length) {
			return rateObj.weChatOrAliPayRate
		}
	}, [rateObj])

	const surplus = useMemo(() => {
		if (Object.keys(rateObj).length) {
			return rateObj.rechargeDiscount
		}
	}, [rateObj])

	useEffect(() => {
		showText = false;
		getRechargeRateFunc()//费率
	}, [])

	//费率
	const getRechargeRateFunc = async () => {
		setLoading(true);
		const params = {};
		if(accountMsg.merchantNo) {
			params.accountNo = accountMsg.merchantNo;
			params.accountType = 2;
		}
		const { success, data = {} } = await getUnionRechargeRateOp(params);
		let timer = setTimeout(() => {
			setLoading(false)
			clearTimeout(timer)
			timer = null
		}, 300)
		if (success) {
			setRateObj(data)
		}
	}

	//充值
	const onFinish = async () => {
		if (loading) {
			return
		}
		if (!rote || !surplus) {
			Modal.info({ content: '如若确保已经开通电子账户，请稍后再试' })
			return
		}
		form.validateFields(['amount']).then(async () => {
			const params = customTrimFunc({
				disAmount:Number(disAmount).toFixed(2),
				orderSrc: 1,
				payAmount: Number(finallyAmount).toFixed(2),
				freeAmount: Number(serviceFee).toFixed(2),
			})
			if(accountMsg.merchantNo) {
				params.accountNo = accountMsg.merchantNo;
				params.accountType = 2;
			}
			setLoading(true)
			const { success, data } = await getPayQrcodeOp(params)
			let timer = setTimeout(() => {
				setLoading(false)
				clearTimeout(timer)
				timer = null
			}, 300)
			if (success) {
				const { dimensionalCode, payOrderSn } = data
				setQrcode(dimensionalCode)
				timerPoll = setInterval(async () => {//充值后轮询
					const { data } = await pollFuncOp({ payOrderSn })
					if (data == 3) {
						closeQrCodeModal()
						closePayModal()
						reloadFunc()
					}
				}, 5000)
				deadlineTimer = setTimeout(() => {
					closeQrCodeModal();
				}, 1800000)
			}
		}).catch(() => {
			Modal.info({ content: '请按照要求输入充值金额' })
		})
	};

	//计算手续费 可到账金额
	const computeServiceFee = () => {
		form.validateFields(['amount']).then(async (res) => {
			const comp = Math.ceil(((res.amount * 100) * (rote * 10000)) / 10000) / 100;
			if (surplus && surplus - 0 >= comp) {//剩余额度够用
				showText = true
				backAmount = Math.ceil(res.amount * 100) / 100
				setFee('0.00')
				setDisAmount(Math.ceil(comp * 1000) / 1000)//防止数字类型的2.00 展示 2
				setAmount(res.amount)
				return
			}
			showText = false
			backAmount = (res.amount * 100 - Math.ceil(comp * 100)) / 100
			setFee(Math.ceil(comp * 1000) / 1000)
			setDisAmount('0.00')
			setAmount(res.amount)
		}).catch(() => {
			showText = false
			backAmount = '0.00'
			setFee("0.00")
			setAmount("0.00")
		})
	}

	//关闭支付弹窗
	const closePayModal = () => {
		timerPoll = null;
		deadlineTimer = null;
		showText = false;
		backAmount = '0.00';
		handleVisible(false)
		setRateObj({})
		setFee('0.00')
		setDisAmount('0.00')
		setAmount('0.00')
	}

	//关闭二维码弹窗
	const closeQrCodeModal = (bool) => {
		if (bool) {
			message.info('如已支付，后续请刷新查看最新余额');
		}
		setQrcode('')
		clearInterval(timerPoll)
		timerPoll = null
		clearTimeout(deadlineTimer);
		deadlineTimer = null;
	}

	return (
		<>
			<CommonModal
				title="扫码充值"
				visible={true}
				onOk={onFinish}
				onCancel={closePayModal}
				width="458px"
				minHeight="160px"
			>
				<Form form={form} name="scan-recharge-modal" style={{ display: 'flex', marginTop: 16 }}>
					<Form.Item label={<span className='lable-require'>充值金额</span>}>
						<div style={{ display: 'flex' }}>
							<Form.Item
								name="amount"
								rules={[
									{ required: true, message: '请输入充值金额' },
									({ }) => ({
										validator(rule, value) {
											if (value) {
												const reg = /^(?!0+(?:.0+)?$)(?:[1-9]\d*|0)(?:.\d{1,2})?$/;
												if (!reg.test(value)) {
													return Promise.reject('请正确输入，最多两位小数');
												}
												if (value > 1000000) {
													return Promise.reject('单笔限额一百万');
												}
												if (value < 1) {
													return Promise.reject('充值金额不得小于1元');
												}
											}
											return Promise.resolve();
										},
									}),
								]}
							>
								<Input suffix="元"
									autoComplete="off"
									onChange={() => computeServiceFee()}
									placeholder="请输入充值金额"
								/>
							</Form.Item>
							<span className={`${styles.rote} common-color8`}>(手续费费率：{rote ? `${rote * 100}%` : '***'})</span>
						</div>
					</Form.Item>
				</Form>

				<div style={{ display: 'flex', padding: "12px 8px 0" }}>
					<p style={{ width: '50%' }}>充值手续费：<span className='commom-color9' style={{ color: '#FF2D51' }}>￥{formatAmount(serviceFee)}</span></p>
					<p style={{ width: '50%' }}>实际到账金额：<span className='commom-color9' style={{ color: '#FF2D51' }}>￥{formatAmount(backAmount)}</span></p>
				</div>
			
				{showText && <div className="common-color5" style={{fontSize:'12px',padding: "12px 8px 0"}}>注：该笔支付手续费将由{APP_TITLE}平台补助给客户，若手续费补助额度不足手续费由自己承担，
				<span className="common-color9">您的手续费剩余补助额度为￥{formatAmount(surplus)}</span></div>}

			</CommonModal>

			<CommonModal
				title="扫码充值"
				visible={qrcode}
				footer={[<Button key='cancel' onClick={() => closeQrCodeModal(true)}>取消</Button>]}
				width="480px"
				onCancel={() => closeQrCodeModal(true)}
			>   
				<div style={{position:'relative'}}>
				  <QRCode value={qrcode} style={{ margin: '0 auto 12px' }} />
				  <img src={union_pay_img} alt="" style={{position:'absolute', left: '200px', top: '40px', width:'40px', height:'40px'}}/>
				</div>
				<p style={{ textAlign: 'center', color: 'red' }}>注：请使用支付宝或者微信进行扫码充值</p>
				<p style={{ margin:'-2px 0px 2px 24px', color: 'red', fontSize: '12px' }}>信用卡及花呗充值后提现需30个工作日到账，正常下单不受影响，知悉！</p>
				<p style={{ textAlign: 'center' }}>需要支付金额为 <span style={{ color: 'red' }}>{formatAmount(finallyAmount)}</span> 元，实际到账金额将扣除手续费 <span style={{ color: 'red' }}>{formatAmount(serviceFee)}</span> 元</p>
			</CommonModal>
			<CommonLoading loading={loading} />
		</>
	);
};
